package cn.explink.eap.core.metadata.repository;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import cn.explink.eap.core.common.model.json.DataGrid;
import cn.explink.eap.core.metadata.domain.Metadata;
import cn.explink.eap.core.metadata.domain.MetadataRowMapper;

@Repository
public class MetadataDAO {

	@Autowired
	private JdbcTemplate jdbcTempate = null;

	public void fillMetaData(DataGrid dataGrid) {
		dataGrid.setTotal(this.getMetaDataCount());
		dataGrid.setResults(this.getPageMetadata(dataGrid));
	}

	public List<Metadata> getAllMetaData() {
		String sql = "select * from eap_metadata";

		return this.getJdbcTempate().query(sql, new MetadataRowMapper());
	}

	private List<Metadata> getPageMetadata(DataGrid dataGrid) {
		String sql = this.getQuerySql(dataGrid);

		return this.getJdbcTempate().query(sql, new MetadataRowMapper());
	}

	private int getMetaDataCount() {
		String sql = this.getCountSql();

		return this.getJdbcTempate().queryForInt(sql);
	}

	private String getQuerySql(DataGrid dataGrid) {
		int page = dataGrid.getPage();
		int length = dataGrid.getRows();
		int start = (page - 1) * length;
		return "select * from eap_metadata limit " + start + " , " + length;
	}

	private String getCountSql() {
		return "select count(md_id) from eap_metadata";
	}

	private JdbcTemplate getJdbcTempate() {
		return this.jdbcTempate;
	}

}
